package com.salt.core.oss.minio.config;

import com.salt.core.oss.minio.MinioTemplate;
import com.salt.core.oss.props.OssProperties;
import com.salt.core.oss.rule.OssRule;
import com.salt.core.oss.rule.SaltOssRule;
import io.minio.MinioClient;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description MINIO 自动配置类
 * @Author salt
 * @Date 2020-11-10
 * @Version 1.0.1
 */
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties(OssProperties.class)
@ConditionalOnProperty(value = "salt.oss.name", havingValue = "minio")
public class MinioConfiguration {

    private final OssProperties ossProperties;

    @Bean
    @ConditionalOnMissingBean(OssRule.class)
    public OssRule ossRule() {
        return new SaltOssRule();
    }

    @Bean
    @SneakyThrows
    @ConditionalOnMissingBean(MinioClient.class)
    public MinioClient minioClient() {
        return new MinioClient(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKey(),
                ossProperties.getSecretKey()
        );
    }

    @Bean
    @ConditionalOnMissingBean(MinioTemplate.class)
    @ConditionalOnBean({MinioClient.class, OssRule.class})
    public MinioTemplate minioTemplate(MinioClient minioClient, OssRule ossRule) {
        return new MinioTemplate(minioClient, ossRule, ossProperties);
    }
}
